package com.qst.controller;

import com.qst.pojo.dto.LoginDTO;
import com.qst.pojo.vo.LoginResponseVO;
import com.qst.pojo.dto.RegisterDTO;
import com.qst.service.AuthService;
import com.qst.util.Result;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginResponseVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            LoginResponseVO loginResponseVO = authService.login(loginDTO);
            return Result.success("登录成功", loginResponseVO);
        } catch (RuntimeException e) {
            logger.error("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("登录异常", e);
            return Result.error("登录失败，请稍后重试");
        }
    }

    /**
     * 用户注册
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<LoginResponseVO> register(@Valid @RequestBody RegisterDTO registerDTO) {
        try {
            LoginResponseVO loginResponseVO = authService.register(registerDTO);
            return Result.success("注册成功", loginResponseVO);
        } catch (RuntimeException e) {
            logger.error("注册失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("注册异常", e);
            return Result.error("注册失败，请稍后重试");
        }
    }
}

